package com.hxzy.common.easyexcel.conver;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * 获取外网图片，写入到excel单元格中
 * https://blog.csdn.net/qq_41915325/article/details/126876852
 * @author Administrator
 */
@Log4j2
public class UrlToImageConver implements Converter<String> {


    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) throws Exception {
        String imageUrl=context.getValue();
        // url地址为空
        if(StrUtil.isBlank(imageUrl)){
            return  new WriteCellData<>("图片地址为空");
        }

        // spring ioc获取对象
        RestTemplate restTemplate = SpringUtil.getBean("restTemplate",RestTemplate.class);

        try {
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(imageUrl, HttpMethod.GET, null, byte[].class);
            //获取entity中的数据
            byte[]  body = responseEntity.getBody();

            //把图片写入到excel表中
            return new WriteCellData<>(body);

        }catch(Exception e){
            log.error(e);
            return  new WriteCellData<>("图片访问失败");
        }

    }
}
